﻿

using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using Modbus.Device;
using Modbus.Utility;

namespace TempHum.service
{
    class modbusUtil
    {
       
       
        public static SerialPort getSerialPort(string port) {
            SerialPort serialPort = new SerialPort();
            serialPort.PortName = port;
            serialPort.BaudRate = 9600;
            serialPort.DataBits = 8;
            serialPort.StopBits = StopBits.One;
            serialPort.Parity = Parity.None;
            return serialPort;
        }
        public static byte[] getSingleCoilMessage(short startAdr, bool value) {
            List<byte> temp = new List<byte>();
            temp.Add(0x01);//从站地址固定为1
            temp.Add(0x05);
            byte[] start = BitConverter.GetBytes(startAdr);
            if (BitConverter.IsLittleEndian) Array.Reverse(start);
            temp.Add(start[0]);
            temp.Add(start[1]);
            temp.Add(0x00);
            temp.Add((byte)(value ? 0x01 :0x00));
            byte[] result = temp.ToArray();
            byte[] crc = ModbusUtility.CalculateCrc(result);
            return result.Concat(crc).ToArray();
        }
        public static byte[] testCom()
        {
            List<byte> temp = new List<byte>();
            temp.Add(0x01);//从站地址固定为1
            temp.Add(0x03);
            temp.Add(0x00);
            temp.Add(0x00);
            temp.Add(0x00);
            temp.Add(0x01);
            byte[] result = temp.ToArray();
            Console.WriteLine(result.Length);
            byte[] crc = ModbusUtility.CalculateCrc(result);
            Console.WriteLine(crc.Length);
            Console.WriteLine(String.Join("", result.Concat(crc).ToArray()));
            return result.Concat(crc).ToArray();
        }
    }
}
